#!/bin/sh

# Copyright 2022 Felix Freeman <libsys@hacktivista.org>
#
# This script is licensed under the 'MIT No Attribution' license terms. I don't
# want attribution nor exclusive rights over it, but I'd love that you free your
# software too.

if [ "$HAWESE_ENV" = 'development' ]; then
	mkdir -p ~/.config/composer
	cat <<- EOF > ~/.config/composer/config.json
	{
	  "repositories": [
	EOF

	for project in $PROJECTS; do
		project_dir=${project#hawese-}
		if [ ! -d "$project_dir" ]; then
			git clone "https://git.hackware.cl/$project" "$project_dir"
		fi
		if [ "$project" != 'userland' ]; then
			cat <<- EOF >> ~/.config/composer/config.json
			    {
			      "type": "path",
			      "url": "/opt/hawese/$project_dir/",
			      "options": {
			        "symlink": true
			      }
			    },
			EOF
		fi
	done

	sed -i -e '$ s/.$//' ~/.config/composer/config.json
	printf "  ]\n}\n" >> ~/.config/composer/config.json
fi

for project in $PROJECTS; do
	if [ ! -d "$project" ]; then
		test "$project" != 'userland' && test "$project" != 'hawese-core' \
			&& composer require --no-install "hackware/$project=*"
	fi
done

composer install
composer run collect-public

cat << EOF > .env
APP_NAME='Hackware Web Services'
APP_ENV=$(test "$HAWESE_ENV" = 'development' && echo 'local' || echo "$HAWESE_ENV")
APP_KEY=$(pwgen -sc 36)
APP_DEBUG=true
APP_URL=https://$ENDPOINT
APP_TIMEZONE=America/Santiago

CORS_ALLOW_ORIGINS=https://$CORS_ENDPOINT

LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=$DB_NAME
DB_USERNAME=$DB_USER
DB_PASSWORD='$DB_PASS'

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=hello@example.com
MAIL_FROM_NAME="Example app"

CACHE_DRIVER=file
QUEUE_CONNECTION=sync

EOF

case "$PROJECTS" in *wallet*) cat <<- EOF >> .env
	WALLET_SOURCE_URL=https://git.hackware.cl/hawese-wallet
	WALLET_TRANSACTION_TYPES=hawese_payment
	WALLET_DUE_AFTER='1 month'
	WALLET_ADD_FUNDS_URL=${WALLET_ADD_FUNDS_URL:-https://$CORS_ENDPOINT/add-funds}
	WALLET_REMIND_DUE='1 day, 2 days, 3 days, 1 week'
	PAYMENT_WALLET_ENDPOINT=https://$ENDPOINT
	EOF
esac

case "$PROJECTS" in *payment*) cat <<- EOF >> .env
	PAYMENT_SOURCE_URL=https://git.hackware.cl/hawese-payment
	PAYMENT_RETURN_URL=${PAYMENT_RETURN_URL:-https://$CORS_ENDPOINT/add-funds/verify}
	PAYMENT_CORE_AUTH_TOKEN=
	KHIPU_RECEIVER_ID=
	KHIPU_SECRET_KEY=
	FLOW_API_KEY=
	FLOW_SECRET_KEY=
	FLOW_TEST_MODE=true
	EOF
esac

case "$PROJECTS" in *userland*)
	cd userland
	npm install
	echo VUE_APP_HAWESE_ENDPOINT="https://$ENDPOINT" > .env
	npm run build
	cd -
esac

php artisan migrate
initial_token=$(composer run seed | sed -ne 's/Initial system token: \(.*\)/\1/p')
sed -i -e "s/PAYMENT_CORE_AUTH_TOKEN=/PAYMENT_CORE_AUTH_TOKEN=$initial_token/" .env
